/** Part of Zombie Navigator
	Copyright © 2016  Zombie Navigator Developers
	
	@file
	@module
	@license AGPL-3.0+
	
*/ 'use strict';


/* Addon SDK dependencies */
const _sdkTabs = require('sdk/tabs');

/* Used modules */
const _pMeta = require('./meta');
const _pOptions = require('./options');


/* Internal APIs */

/**
	Open an addon UI in a new window
	@public
	@method
	@param {string} uri
	@param {object} acceptCommands
	@returns {boolean}
*/
const openPopup = (uri, acceptCommands) => {
	const pOptions = _pOptions;
	
	uri = uri ? uri + '' : 'about:blank';
	if (!pOptions.activeUiEnabled()) acceptCommands = void(0);
	
	const sdkTabs = _sdkTabs;
	
	try {
		let once = true;
		
		sdkTabs.open({
			url: uri
			, inNewWindow: true
			, onReady: sdkTab => {
				// It is important to revoke permissions to linked pages
				if (!once) return;
				once = false;
				
				if ('object' == typeof acceptCommands && null != acceptCommands) {
					// Trivial static contentScript on addon UIs
					const worker = sdkTab.attach({
						contentScript: `
'use strict';

exportFunction((name, data) => {
	try {
		self.port.emit('command', {name: name, data: data});
	} catch (e) {
		console.warn(e+'');
	}
}, window.unsafeWindow, {defineAs: 'zombieCommand'});
`
						// end of contentScript
					});
					
					worker.port.on('command', m => {
						const {name, data} = m;
						
						if ('string' != typeof name) return;
						if ('function' != typeof acceptCommands[name]) return;
						
						acceptCommands[name](data);
					});
				}
			}
		});
	} catch (e) {
		throw new Error(e + '');
	}
	
	return true;
};

/** @public
	@method */
const openPreferences = isPrivate => {
	const pOptions = _pOptions;
	const sdkTabs = _sdkTabs;
	
	if (!pOptions.activeUiEnabled()) return;
	
	let once = true;
	
	sdkTabs.open({
		url: 'about:addons'
		,isPrivate: !!isPrivate
		,onReady: sdkTab => {
			if (!once) return;
			once = false;
			
			const {getProductID} = _pMeta;
			
			// Trivial static contentScript on about:addons
			const worker = sdkTab.attach({
				contentScript: `
(() => {
	'use strict';
	
	self.port.on('open-prefs', addonID => {
		AddonManager.getAddonByID(addonID, addon => {
			unsafeWindow.gViewController.commands.cmd_showItemDetails
				.doCommand(addon, true);
		});
	});
	
	self.postMessage(true); // Done!
})();
`
				// end of contentScript
				,onMessage: () => worker.port.emit('open-prefs', getProductID())
			});
		}
	});
};

/* Exports */
exports.openPopup = openPopup;
exports.openPreferences = openPreferences;


// vim: ts=4 noet ai

